package com.atguigu.flink.demo02;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import java.util.Arrays;

/**
 * 编写wordcount程序
 * @author admin
 * @date 2021/8/6
 */
public class Demo001 {

    public static void main(String[] args) throws Exception {

        // 创建环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        // 读取由外部传入的文件地址
        DataStreamSource<String> streamSource = env.readTextFile(args[0]);

        // 处理文件中的每行数据
        SingleOutputStreamOperator<Tuple2<String, Integer>> operator = streamSource.flatMap((FlatMapFunction<String, Tuple2<String, Integer>>) (lines, out) -> {
            // 切割并将数据收集
            Arrays.stream(lines.split(" ")).forEach(s -> out.collect(Tuple2.of(s, 1)));
        }).returns(Types.TUPLE(Types.STRING, Types.INT));

        // 计算每个单词的个数
        SingleOutputStreamOperator<Tuple2<String, Integer>> sum = operator.keyBy(0).sum(1);

        // 打印
        sum.print("test");

        // 开启
        env.execute();
    }
}
